package cn.bdqn.service.impl;

import cn.bdqn.bean.result.Page;
import cn.bdqn.domain.Purchase;
import cn.bdqn.domain.PurchaseInfo;
import cn.bdqn.mapper.PurchaseMapper;
import cn.bdqn.mapper.PurchaseInfoMapper;
import cn.bdqn.service.PurchaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (Purchase)表服务实现类
 *
 * @author makejava
 * @since 2020-09-21 10:54:12
 */
@Service("purchaseService")
public class PurchaseServiceImpl implements PurchaseService {
    @Resource
    private PurchaseMapper purchaseMapper;
    @Resource
    PurchaseInfoMapper purchaseinfoMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Purchase queryById(Integer id) {
        return this.purchaseMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Purchase> queryAllByLimit(int offset, int limit) {
        return this.purchaseMapper.queryAllByLimit(offset, limit);
    }


    /**
     * 新增数据
     *同时向采购详情表添加信息
     * @param purchase 实例对象
     * @return 实例对象
     */
    @Override
    public Purchase insert(Purchase purchase) {
        purchase.setpDate(new Date());
        //获取到需要采购的药品
        //同时向采购详情表添加数据
        List<PurchaseInfo> purchaseinfos=purchase.getPurchaseinfoList();
        for (PurchaseInfo purchaseinfo:purchaseinfos){
            purchaseinfo.setPNumber(purchase.getpNumber());
            purchaseinfoMapper.insert(purchaseinfo);
        }
        this.purchaseMapper.insert(purchase);
        return purchase;
    }

    /**
     * 修改数据
     *
     * @param purchase 实例对象
     * @return 实例对象
     */
    @Override
    public Purchase update(Purchase purchase) {
        this.purchaseMapper.update(purchase);
        return this.queryById(purchase.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.purchaseMapper.deleteById(id) > 0;
    }

    /**
     * 分页显示多条件查询信息
     */
    @Override
    public Page<Purchase> queryAll(Integer startNum, Purchase purchase) {
        Page page=new Page();
        PageHelper.startPage(startNum != null ? startNum:1,page.getPageSize());
        List<Purchase> purchases= purchaseMapper.queryAll(purchase);
        PageInfo<Purchase> pageInfo=new PageInfo<>(purchases);
        page.setMenuList(pageInfo.getList());
        return page;
    }
}